<template>
  <div class="box">
    <div class="header-box">
      <a-alert type="warning">
        <template #description>
          <p>佣金是根据固定时间结算，结算日自行设置。只有到了每个月的结算日才会将这段时间的合同根据当前佣金比例进行计算。在结算日之后发生的变更不会影响佣金计算。</p>
        </template>
      </a-alert>
    </div>
    <!-- 顶部数据 -->
    <div class="header">
      <a-row type="flex" align="middle" justify="center">
        <a-col :flex="1" style="text-align: center">
          <div class="num-info">
            {{ total_commission_price }}
          </div>
          <div>
            佣金总额
            <a-tooltip>
              <template #title> 佣金总额=已付款金额+待付款金额</template>
              <QuestionCircleOutlined />
            </a-tooltip>
          </div>
        </a-col>
        <a-divider
          type="vertical"
          style="height: 20px; background-color: #eee"
        />
        <a-col :flex="1" style="text-align: center">
          <div class="num-info">
            {{ total_paid_price }}
          </div>
          <div>
            已付金额
            <a-tooltip>
              <template #title>生成付款单并且状态为已结清的金额</template>

              <QuestionCircleOutlined />
            </a-tooltip>
          </div>
        </a-col>
        <a-divider
          type="vertical"
          style="height: 20px; background-color: #eee"
        />
        <a-col :flex="1" style="text-align: center">
          <div class="num-info">{{ total_unpaid_price }}</div>
          <div>
            待付金额
            <a-tooltip>
              <template #title
                >在生成付款单并且状态为已结清之前的所有状态的金额</template
              >
              <QuestionCircleOutlined />
            </a-tooltip>
          </div>
        </a-col>
      </a-row>
    </div>

    <div class="mt-10">
      <a-radio-group
        v-model:value="source"
        button-style="solid"
        @change="sourceChange"
      >
        <a-radio-button :value="1">团队结算</a-radio-button>
        <a-radio-button :value="2">渠道结算</a-radio-button>
      </a-radio-group>
    </div>

    <div
      class="mt-10 mb-10"
      style="display: flex; justify-content: space-between"
    >
      <div class="flex-1">
        <a-row :gutter="[9, 9]" :wrap="true">
          <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
            <a-date-picker
              style="width: 100%"
              v-model:value="month"
              :format="monthFormat"
              picker="month"
              @change="monthChange"
              :allowClear="false"
          /></a-col>
          <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24" v-if="source == 1">
            <a-select
              style="width: 100%"
              :options="groupOptions"
              v-model:value="team_id"
              placeholder="选择团队"
            >
            </a-select
          ></a-col>
          <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24" v-if="source == 2"
            ><a-select
              style="width: 100%"
              :options="chanelList"
              v-model:value="channel_id"
              placeholder="选择渠道"
            >
            </a-select
          ></a-col>
          <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
            <a-input
              style="width: 100%"
              placeHolder="搜索联系人名称"
              v-model:value="user_name"
            ></a-input
          ></a-col>
          <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
            <a-select
              style="width: 100%"
              :options="approval_status_options"
              placeholder="审核状态"
              v-model:value="approval_status"
            >
            </a-select
          ></a-col>

          <a-col>
            <a-space>
              <a-button @click="reSet">重置</a-button>
              <a-button type="primary" @click="toSearch"
                >搜索</a-button
              ></a-space
            >
          </a-col>

          <a-col style="margin-left: auto">
            <a-popconfirm
              title="确认审核并生成付款单?"
              ok-text="确认"
              cancel-text="取消"
              @confirm="getPayOrder"
            >
              <a-button type="primary" v-if="!isAuto"
                >审核并生成付款单</a-button
              >
            </a-popconfirm>
          </a-col>
        </a-row>
      </div>
    </div>

    <a-table
      bordered
      :columns="source == 1 ? teamColumns : channelColumns"
      :dataSource="tableData"
      :pagination="pagination"
      @change="handleTableChange"
      rowKey="id"
      :row-selection="
        isAuto
          ? null
          : {
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }
      "
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key == 'user_info'">
          {{ record.user_name }}/{{ record.user_tel }}
        </template>
        <template v-if="column.key == 'template'">
          {{ record?.commission_template?.name }}
        </template>
        <template
          v-if="
            column.key == 'month' ||
            column.key == 'team_name' ||
            column.key == 'contract_count' ||
            column.key == 'commission_price' ||
            column.key == 'channel_name'
          "
        >
          {{ record[column.key] || "--" }}
        </template>

        <template v-if="column.key == 'approval_status'">
          <a-tag color="blue" v-if="record.approval_status == 1">待审批</a-tag>
          <a-tag color="red" v-if="record.approval_status == 2">待付款</a-tag>
          <a-tag color="red" v-if="record.approval_status == 3">已驳回</a-tag>
          <a-tag color="green" v-if="record.approval_status == 4">已付款</a-tag>
        </template>

        <template v-if="column.key == 'action'">
          <a-button type="link" @click="checkDetail(record.id)">详情</a-button>
          <a-button
            type="link"
            v-if="record.approval_id != 0"
            @click="checkApprove(record.approval_id)"
            >查看审批</a-button
          >
        </template>
      </template>
    </a-table>

    <!-- 详情 -->
    <SettlementDetail
      :visible="showDetail"
      :id="detailId"
      @closeDetail="showDetail = false"
    />
    <!-- 审批详情 -->
    <SettlementApproveDetail
      :id="detailId"
      :visible="showApproveDetail"
      @close="() => (showApproveDetail = false)"
    />
  </div>
</template>

<script>
import { QuestionCircleOutlined } from "@ant-design/icons-vue";
import { reactive, toRefs, ref, computed, watch } from "vue";
import SettlementDetail from "./SettlementDetail.vue";
import SettlementApproveDetail from "./SettlementApproveDetail.vue";
import request from "../../../../common/utils/request";
import { message } from "ant-design-vue";
import { context } from "ant-design-vue/lib/vc-image/src/PreviewGroup";
import dayjs from "dayjs";
const monthFormat = "YYYY-MM";
export default {
  components: {
    QuestionCircleOutlined,
    SettlementDetail,
    SettlementApproveDetail,
  },
  props: {
    activeKey: {
      type: String,
      default: "",
    },
  },
  setup(props, context) {
    const state = reactive({
      source: 1,
      loading: false,
      selectedRowKeys: [],
      detailId: 0,
      isAuto: true,
      total_commission_price: 0,
      total_paid_price: 0,
      total_unpaid_price: 0,
    });

    const teamColumns = [
      {
        title: "月份",
        key: "month",
        width: 100,
      },
      {
        title: "姓名/手机号",
        key: "user_info",
        width: 100,
      },
      {
        title: "关联合同数",
        key: "contract_count",
        width: 100,
      },
      {
        title: "团队",
        key: "team_name",
        width: 100,
      },
      {
        title: "提成模板",
        key: "template",
        width: 100,
      },
      {
        title: "佣金",
        key: "commission_price",
        width: 100,
      },
      {
        title: "状态",
        key: "approval_status",
        width: 100,
      },
      {
        title: "操作",
        key: "action",
        width: 150,
      },
    ];
    const channelColumns = [
      {
        title: "月份",
        key: "month",
        width: 100,
      },
      {
        title: "姓名/手机号",
        key: "user_info",
        width: 100,
      },
      {
        title: "关联合同数",
        key: "contract_count",
        width: 100,
      },
      {
        title: "渠道",
        key: "channel_name",
        width: 100,
      },
      {
        title: "提成模板",
        key: "template",
        width: 100,
      },
      {
        title: "佣金",
        key: "commission_price",
        width: 100,
      },
      {
        title: "状态",
        key: "approval_status",
        width: 100,
      },
      {
        title: "操作",
        key: "action",
        width: 150,
      },
    ];

    // 查看详情
    const showDetail = ref(false);
    const checkDetail = (val) => {
      console.log(val);
      state.detailId = val;
      showDetail.value = true;
    };
    // 查看审批
    const showApproveDetail = ref(false);
    const checkApprove = (val) => {
      state.detailId = val;
      showApproveDetail.value = true;
    };

    const getConfig = () => {
      request.get("/org", "/business/customer/getSettleConfig").then((res) => {
        console.log(res.data);
        state.isAuto = res?.data?.compute_type == 2;
      });
    };

    const groupOptions = ref([]);
    const getGroupList = () => {
      request.get("/org", "/business/customerTeam/teamIndex").then((res) => {
        console.log(res);
        let teamList = res?.data || [];
        groupOptions.value = teamList.map((v) => {
          return {
            label: v.name,
            value: v.id,
          };
        });
      });
    };
    getGroupList();

    // 获取渠道列表
    const chanelList = ref([]);
    const getChannelList = () => {
      request
        .get("/org", "/business/customer/channel/index", {})
        .then((res) => {
          chanelList.value = res.list.map((item) => {
            return {
              value: item.id,
              label: item.name,
            };
          });
        });
    };
    getChannelList();

    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);

    const searchParams = reactive({
      month: "",
      team_id: undefined,
      channel_id: undefined,
      user_name: "",
      approval_status: undefined,
    });
    const tableData = ref([]);

    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));
    const getDataList = () => {
      state.loading = true;
      const param = {
        page: page.value,
        limit: limit.value,
        source_arr: state.source == 1 ? [1, 2] : [3],
      };

      Object.keys(searchParams).forEach((key) => {
        if (searchParams[key]) {
          param[key] = searchParams[key];

          param[key] =
            key == "month"
              ? dayjs(searchParams[key]).format("YYYY-MM")
              : searchParams[key];
        }
      });
      // let month = dayjs().format("YYYY-MM"); //默认当前月份
      // if (!searchParams.month) {
      //   console.log(month);
      //   searchParams.month = month;
      //   param.month = month;
      // }
      request
        .post("/org", "/business/customer/monthSettleList", param)
        .then((res) => {
          console.log(res);
          state.total_commission_price = res?.static?.total_commission_price
            ? res?.static?.total_commission_price
            : 0;
          state.total_paid_price = res?.static?.total_paid_price
            ? res?.static?.total_paid_price
            : 0;
          state.total_unpaid_price = res?.static?.total_unpaid_price
            ? res?.static?.total_unpaid_price
            : 0;
          tableData.value = res.list;
        })
        .finally(() => {
          state.loading = false;
        });
    };

    const handleTableChange = (pager, filters, sorter) => {
      page.value = pager.current;
      limit.value = pager.pageSize;
      getDataList();
    };
    const onSelectChange = (selectedRowKeys) => {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      state.selectedRowKeys = selectedRowKeys;
    };

    const sourceChange = () => {
      if (state.source == 1) {
        searchParams.channel_id = undefined;
      } else {
        searchParams.team_id = undefined;
      }
      getDataList();
    };

    // 重置
    const reSet = () => {
      Object.keys(searchParams).forEach((key) => {
        searchParams[key] =
          key == "team_id" || key == "approval_status" ? undefined : "";
      });
      let month = dayjs().format("YYYY-MM"); //默认当前月份
      searchParams.month = dayjs(month);
      page.value = 1;
      getDataList();
    };
    // 搜索
    const toSearch = () => {
      page.value = 1;
      getDataList();
    };

    // 审核并生成订单
    const getPayOrder = () => {
      if (state.selectedRowKeys.length == 0) {
        message.error("请先选择账单！");
        return;
      }

      console.log(state.selectedRowKeys.length);
      if (state.selectedRowKeys.length == 1) {
        // 单个
        const param = { id: state.selectedRowKeys[0] };
        request
          .get("/org", "/business/customer/handSettleApprove", param)
          .then((res) => {
            console.log(res);
            message.success("操作成功");
            getDataList();
          });
      } else {
        // 多个
        const param = { ids: state.selectedRowKeys };
        request
          .post("/org", "/business/customer/batchSettleApprove", param)
          .then((res) => {
            console.log(res);
            message.success("操作成功");
            getDataList();
          });
      }
    };

    const monthChange = (date, dateString) => {
      console.log(date, dateString);
      // searchParams.month = dayjs(dateString).format("YYYY-MM");
    };

    const init = () => {
      let month = dayjs().format("YYYY-MM"); //默认当前月份
      searchParams.month = dayjs(month);

      getConfig();
      getDataList();
    };

    context.expose({ getConfig });

    watch(
      () => props.activeKey,
      (val) => {
        console.log(val);
        if (val == "list") {
          init();
        }
      },
      {
        immediate: true,
      }
    );

    const approval_status_options = [
      {
        label: "已审核",
        value: 1,
      },
      {
        label: "待付款",
        value: 2,
      },
      {
        label: "已驳回",
        value: 3,
      },
      {
        label: "已付款",
        value: 4,
      },
    ];

    return {
      ...toRefs(state),
      ...toRefs(searchParams),
      teamColumns,
      channelColumns,
      tableData,
      checkDetail,
      checkApprove,
      showDetail,
      groupOptions,
      handleTableChange,
      onSelectChange,
      getPayOrder,
      page,
      limit,
      pagination,
      total,
      showApproveDetail,
      sourceChange,
      toSearch,
      reSet,
      approval_status_options,
      monthFormat,
      monthChange,
      chanelList,
    };
  },
};
</script>

<style lang="less" scoped>
.box {
  padding: 10px;

  .header {
    background-color: rgb(240, 242, 245);
    padding: 10px;

    .num-info {
      color: #2681f3;
      font-size: 30px;
    }
  }

  .w-120 {
    width: 120px;
    margin-right: 10px;
  }
  .m-t-10 {
    margin-top: 10px;
  }
}
.header-box {
  margin-bottom: 10px;
}
:deep(.ant-alert-description) {
  font-size: 12px;
  p {
    margin-bottom: 6px;
    &:last-of-type {
      margin-bottom: 0;
    }
  }
}
:deep(.ant-alert-with-description.ant-alert-no-icon) {
  padding: 6px 10px;
}
</style>
